# coding=utf-8

import sqlite3  # 数据库模块
from bs4 import BeautifulSoup  # 网页解析模块
import urllib.request, urllib.error  # 网页数据
import xlwt, re

findLink = re.compile(r'<a href="(.*?)">')
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)  # 忽略换行符 ，包含进去
findTitle = re.compile(r'<span class="title">(.*)</span>')  # 标题
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')  # 评分
findJudge = re.compile(r'<span>(\d*)人评价</span>')
findIng = re.compile(r'<span class="inq">(.*)</span>')  # 概括
findBD = re.compile(r'<p class="">(.*?)</p>', re.S)  # 去掉换行符，否则会出现超界


def main():
    baseurl = "https://movie.douban.com/top250?start="

    datalist = getData(baseurl)
    savepath = r".\\doubantop250.xls"
    saveData(datalist, savepath)


# 爬取网页
def getData(baseurl):
    datalist = []
    for i in range(0, 10):
        url = baseurl + str(i * 25)
        html = askURL(url)
        # 提取数据
        soup = BeautifulSoup(html, 'html.parser')
        for item in soup.find_all('div', class_="item"):  # 从DIV 解析出模块
            data = []
            item = str(item)

            link = re.findall(findLink, item)[0]  # 读取 链接 图片标题 评分，简介
            data.append(link)
            imgSrc = re.findall(findImgSrc, item)[0]
            data.append(imgSrc)
            titles = re.findall(findTitle, item)
            if len(titles) == 2:
                ctitle = titles[0]
                data.append(ctitle)  # 中文名
                ottitle = titles[1].replace("/", "")
                ottitle = ottitle.strip()
                data.append(ottitle)  # 外国名 如果没有 就留空
            else:
                data.append(titles[0].strip())
                data.append(" ")
            rating = re.findall(findRating, item)[0]
            data.append(rating)
            judge = re.findall(findJudge, item)[0]
            data.append(judge)
            Ing = re.findall(findIng, item)
            if len(Ing) != 0:
                Ing = Ing[0].replace("。", "")
            else:
                Ing = " "
            data.append(Ing)
            bd = re.findall(findBD, item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)?', " ", bd)
            bd = bd.strip()
            data.append(bd)

            datalist.append(data)
    return datalist


# 指定url的网页内容
def askURL(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"}
    reqquest = urllib.request.Request(url=url, headers=head)
    html = ''''''
    try:
        response = urllib.request.urlopen(reqquest)
        html = response.read()
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "resion"):
            print(e.resion)

    return html


# 保存数据
def saveData(dataist, savepath):
    workbook = xlwt.Workbook(encoding='utf-8')
    worksheet = workbook.add_sheet('豆瓣电影TOP250', cell_overwrite_ok=True)
    col = ("电影详情链接", "图片连接", "影片中文名", "影片英文名", "评分", "评价人数", "概况", "相关信息")
    for i in range(0, 8):
        worksheet.write(0, i, col[i])
    for i in range(0, 250):
        print('i', i)
        data = dataist[i]
        for j in range(0, 8):
            worksheet.write(i + 1, j, data[j])

    workbook.save(savepath)  # 保存


if __name__ == '__main__':
    main()
